import { genTestUserSig } from "@/pages/TUIKit/debug";
import { TIM, TIMUploadPlugin, Aegis } from '@/pages/TUIKit/debug/tim.js';
import {TUIConversationServer, TUIProfileServer} from "@/pages/TUIKit/TUICore/server";
const aegis = new Aegis({
  id: 'iHWefAYqmGKHeAqvDB', // 项目key
  reportApiSpeed: true, // 接口测速
});
uni.$aegis = aegis;
const config = {
  userID: '', //User ID
  SDKAppID: 1400792703, // Your SDKAppID
  secretKey: 'c04e8a9412dd7cff393e5341e51331a79f822abcbc7bb64eb891e65d14740b5f', // Your secretKey
};
uni.$chat_SDKAppID = config.SDKAppID;
uni.$chat_userID = config.userID;
// 创建 sdk 实例
uni.$TUIKit = TIM.create({
  SDKAppID: uni.$chat_SDKAppID,
});
uni.$TIM = TIM;
// 注册文件上传插件
uni.$TUIKit.registerPlugin({
  "tim-upload-plugin": TIMUploadPlugin,
});
export const login = (userId: string) => {
  config.userID = userId
  const userSig = genTestUserSig(config).userSig;
  uni.$chat_userSig = userSig;
  // login TUIKit
  uni.$TUIKit.login({ userID: config.userID, userSig }).then((res) => {
    // sdk 初始化，当 sdk 处于ready 状态，才可以使用API，文档
    // uni.showLoading({
    //   title: "初始化...",
    // });
  });
}
export const bindTIMEvent = () => {
  uni.$TUIKit.on(uni.$TIM.EVENT.SDK_READY, handleSDKReady);
  uni.$TUIKit.on(uni.$TIM.EVENT.SDK_NOT_READY, handleSDKNotReady);
  uni.$TUIKit.on(uni.$TIM.EVENT.KICKED_OUT, handleKickedOut);
}
// sdk ready 以后可调用 API
const handleSDKReady = (event) => {
  uni.$chat_isSDKReady = true;
  uni.hideLoading();
  uni.$TUIKit.TUIConversationServer = new TUIConversationServer();
  uni.$TUIKit.TUIProfileServer = new TUIProfileServer();
  // uni.navigateTo({
  //   url: "/pages/TUIKit/TUIPages/TUIConversation/index",
  // });
}
const handleSDKNotReady = (event) => {
  uni.showToast({
    title: "SDK 未完成初始化",
  });
}
const kickedOutReason = (type) => {
  switch (type) {
    case uni.$TIM.TYPES.KICKED_OUT_MULT_ACCOUNT:
      return "多实例登录";
    case uni.$TIM.TYPES.KICKED_OUT_MULT_DEVICE:
      return "多设备登录";
    case uni.$TIM.TYPES.KICKED_OUT_USERSIG_EXPIRED:
      return "userSig 过期";
    case uni.$TIM.TIM.TYPES.KICKED_OUT_REST_API:
      return "REST API kick 接口踢出";
    default:
      return "";
  }
}
const handleKickedOut = (event) => {
  uni.clearStorageSync();
  uni.showToast({
    title: `${kickedOutReason(event.data.type)}被踢出。`,
    icon: "none",
  });
}